package com.hugoo.imp.buzz;

import com.hugoo.ajxl.exception.ExcelException;
import com.hugoo.ajxl.util.ExcelUtils;
import com.hugoo.core.Conf;
import com.hugoo.imp.buzz.mo.ColumnInfo;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import jxl.Workbook;
import jxl.format.Colour;
import jxl.format.UnderlineStyle;
import jxl.write.*;

/**
 *
 * @author Lovelock.Chan
 */
public class ImpInfoBuzz extends FileInfo {

    public ImpInfoBuzz(String sid) {
        super(sid);
    }

    public ImpInfoBuzz(String sid, String cust) {
        super(sid, null, cust);
    }

    @Override
    protected void __buildSysColumn(List<ColumnInfo> col) {
    }

    protected String getImpFileType() {
        return Conf.getImpProp(_sid, Conf.IMP._imp_type);
    }

    protected String getImpFileDesc() {
        String t = getImpFileType();
        if ("TXT".equalsIgnoreCase(t)) {
            return "文本文件（*.txt）";
        } else if ("XLS".equalsIgnoreCase(t)) {
            return "Excel 2003文件（*.xls）";
        } else {
            return "配置错误【无效类型】";
        }
    }

    public String info(String oth) {
        StringBuilder sb = new StringBuilder();
        sb.append("<form name='").append(_sid).append("' action='").append(_sid).append(".imp?m=upload' enctype='multipart/form-data' method='post'>"
                + "<table border='0'>");
        sb.append("<caption>").append(getTitle()).append("导入</caption>");
        sb.append("<tbody><tr><th>数据名称：</th><td>").append(getTitle()).append("</td></tr>");
        sb.append("<tr><th>导入字段描述：</th><td>").append(getColumnTitle()).append("</td></tr>");
        sb.append("<tr><th>导入字段规则：</th><td>详细字段规则，请查看<img src='tpl/img/math.gif'/><a href='").append(_sid).append(".imp?m=download&type=rule'>下载附件</a>。</td></tr>");
        sb.append("<tr><th>导入文件类型：</th><td>").append(getImpFileDesc()).append("</td></tr>");
        sb.append("<tr><th>导入文件：</th><td><input name='impfile' type='file' flt='").append(getImpFileType()).append("' /></td></tr>");
        sb.append("<tr><th>模板下载：</th><td><img src='tpl/img/math.gif'/><a href='").append(_sid).append(".imp?m=download&type=templete'>文件模板下载</a></td></tr>");
        sb.append("<tr><th>其它说明：</th><td><ol>"
                + "<li>本功能只支持").append(getImpFileDesc()).append("类型导入，其它文件无效。"
                + "<li>导入内容请按照指定规则提供，以确保数据的正确性。"
                + "<li>本文件的数据只有在通过数据验证【审核】后，才会导入到数据库中，固数据的实际导入会存在延迟，请耐心等候。"
                + "</ol></td></tr>");
        sb.append("<tr><td colspan='2' align='center'><input type='submit' id='UP_SUBMIT' value='上传数据'/><input type='button' id='UP_BACK' onclick=\"window.location.href='").append(_sid).
                append(".imp?m=load'\"  value='返回列表'/></td></tr>");
        sb.append("</tbody></table>");
        sb.append(oth);
        sb.append("</form>");
        return sb.toString();
    }

    public File getTemplete() throws IOException {
        String t = getImpFileType();
        fileName = getTitle() + "模板文件." + t.toLowerCase();
        File tpl = getTempFile();
        if ("TXT".equalsIgnoreCase(t)) {
            FileWriter fr = new FileWriter(tpl);
            fr.write(col_title);
            fr.close();
        } else if ("XLS".equalsIgnoreCase(t)) {

            WritableWorkbook ww = Workbook.createWorkbook(tpl); // 建立excel文件
            WritableSheet ws = ww.createSheet("模板单元", 0);// sheet名称
            // 设置excel列名字体
            WritableFont wfont = new WritableFont(WritableFont.ARIAL, 10, WritableFont.BOLD, false, UnderlineStyle.NO_UNDERLINE, Colour.BLACK);
            WritableCellFormat wcfFc = new WritableCellFormat(wfont);
            Label wlabel;
            //创建Excel的列名
            try {
                int i = 0, r = 0;
                for (ColumnInfo ci : col) {
                    wlabel = new Label(i++, r, ci.getDesc(), wcfFc);
                    ws.addCell(wlabel);
                }
                ww.write();//写入文件
            } catch (Exception e) {
                log.warn("写入Xls文件时，出现异常！", e);
            } finally {
                if (ww != null) {
                    try {//关闭
                        ww.close();
                    } catch (Exception ex) {
                        log.warn("关闭Xls文件时，出现异常！", ex);
                    }
                }
            }
        }
        return tpl;
    }

    protected File getTempFile() throws IOException {
        File tmpFile = File.createTempFile(UUID.randomUUID().toString(), null);
        return tmpFile;
    }

    public File getRules() throws IOException {
        File tpl = getTempFile();
        try {
            fileName = getTitle() + "规则文件.xls";
            String xtpl = ImpInfoBuzz.class.getResource("/prop/tpl/ImpFileRules.xls").getPath();
            Map m = new HashMap();
            {
                m.put("rs", col);
            }
            ExcelUtils.export(xtpl, m, new FileOutputStream(tpl));
        } catch (ExcelException ex) {
            log.warn("生成规则文件失败！", ex);
        }
        return tpl;
    }
    private String fileName;

    public String getFileName(String tpe) {
        return fileName;
    }
}
